package lc.com.lcpicturebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lc.com.lcpicturebackend.manager.upload.FilePictureUpload;
import lc.com.lcpicturebackend.mapper.CarouselConfigMapper;
import lc.com.lcpicturebackend.mapper.CarouselItemMapper;

import lc.com.lcpicturebackend.model.dto.carousel.CarouselConfigRequest;
import lc.com.lcpicturebackend.model.dto.carousel.CarouselImageUploadRequest;
import lc.com.lcpicturebackend.model.dto.flie.UploadPictureResult;
import lc.com.lcpicturebackend.model.entity.CarouselConfig;
import lc.com.lcpicturebackend.model.entity.CarouselItem;
import lc.com.lcpicturebackend.service.CarouselService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图服务实现
 */
@Service
public class CarouselServiceImpl extends ServiceImpl<CarouselItemMapper, CarouselItem> implements CarouselService {

    @Resource
    private CarouselConfigMapper carouselConfigMapper;

    @Resource
    private CarouselItemMapper carouselItemMapper;

    @Resource
    private FilePictureUpload filePictureUpload;

    // 默认场景
    private static final String DEFAULT_SCENE = "home";

    /**
     * 获取轮播图配置
     */
    @Override
    public CarouselConfigRequest getCarouselConfig(String scene) {
        // 如果未指定场景，使用默认场景
        if (scene == null || scene.isEmpty()) {
            scene = DEFAULT_SCENE;
        }

        // 获取配置
        CarouselConfig config = getConfigByScene(scene);

        // 获取轮播图项
        QueryWrapper<CarouselItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scene", scene)
                .eq("status", 1)
                .eq("isDelete", 0)
                .orderByAsc("sort")
                .orderByDesc("createTime");
        List<CarouselItem> itemList = carouselItemMapper.selectList(queryWrapper);

        // 转换为DTO
        CarouselConfigRequest result = new CarouselConfigRequest();

        // 组装配置
        CarouselConfigRequest.CarouselConfigData configData = new CarouselConfigRequest.CarouselConfigData();
        BeanUtils.copyProperties(config, configData);
        result.setConfig(configData);

        // 组装轮播项
        List<CarouselConfigRequest.CarouselItemData> itemDataList = new ArrayList<>();
        for (CarouselItem item : itemList) {
            CarouselConfigRequest.CarouselItemData itemData = new CarouselConfigRequest.CarouselItemData();
            BeanUtils.copyProperties(item, itemData);
            itemDataList.add(itemData);
        }
        result.setItems(itemDataList);

        return result;
    }

    /**
     * 保存轮播图配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCarouselConfig(CarouselConfigRequest carouselConfigRequest, String scene) {
        // 如果未指定场景，使用默认场景
        if (scene == null || scene.isEmpty()) {
            scene = DEFAULT_SCENE;
        }

        // 保存配置
        CarouselConfig config = getConfigByScene(scene);
        BeanUtils.copyProperties(carouselConfigRequest.getConfig(), config);
        // 确保场景值正确
        config.setScene(scene);

        if (config.getId() == null) {
            carouselConfigMapper.insert(config);
        } else {
            carouselConfigMapper.updateById(config);
        }

        // 处理轮播图项
        // 如果提供了轮播项，则先删除原有的，再插入新的
        if (carouselConfigRequest.getItems() != null && !carouselConfigRequest.getItems().isEmpty()) {
            LambdaUpdateWrapper<CarouselItem> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CarouselItem::getScene, scene)
                    .eq(CarouselItem::getIsDelete, 0)
                    .set(CarouselItem::getIsDelete, 1);
            carouselItemMapper.update(null, updateWrapper);


            // 插入新的轮播项
            List<CarouselConfigRequest.CarouselItemData> itemDataList = carouselConfigRequest.getItems();
            for (int i = 0; i < itemDataList.size(); i++) {
                CarouselConfigRequest.CarouselItemData itemData = itemDataList.get(i);
                CarouselItem item = new CarouselItem();
                BeanUtils.copyProperties(itemData, item);
                // 设置场景
                item.setScene(scene);
                // 设置排序值
                item.setSort(i);
                // 默认状态为启用
                item.setStatus(1);
                // 确保是新记录
                item.setId(null);

                carouselItemMapper.insert(item);
            }
        }

        return true;
    }

    /**
     * 获取指定场景的配置（如果不存在则创建）
     */
    private CarouselConfig getConfigByScene(String scene) {
        QueryWrapper<CarouselConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scene", scene).eq("isDelete", 0);
        CarouselConfig config = carouselConfigMapper.selectOne(queryWrapper);

        if (config == null) {
            // 不存在则创建默认配置
            config = new CarouselConfig();
            config.setScene(scene);
            config.setAutoplay(true);
            config.setAutoplaySpeed(3000);
            config.setDots(true);
            config.setEffect("scrollx");
            carouselConfigMapper.insert(config);
        }

        return config;
    }

    /**
     * 获取轮播图项列表
     */
    @Override
    public List<CarouselItem> listCarouselItems(String scene) {
        // 如果未指定场景，使用默认场景
        if (scene == null || scene.isEmpty()) {
            scene = DEFAULT_SCENE;
        }

        QueryWrapper<CarouselItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scene", scene)
                .eq("isDelete", 0)
                .orderByAsc("sort")
                .orderByDesc("createTime");
        return carouselItemMapper.selectList(queryWrapper);
    }

    /**
     * 添加轮播图项
     */
    @Override
    public CarouselItem addCarouselItem(CarouselItem carouselItem) {
        // 如果未指定场景，使用默认场景
        if (carouselItem.getScene() == null || carouselItem.getScene().isEmpty()) {
            carouselItem.setScene(DEFAULT_SCENE);
        }

        // 设置默认排序值
        if (carouselItem.getSort() == null) {
            // 获取最大排序值（按场景）
            Integer maxSort = carouselItemMapper.selectMaxSortByScene(carouselItem.getScene());
            carouselItem.setSort(maxSort == null ? 0 : maxSort + 1);
        }

        // 设置默认状态
        if (carouselItem.getStatus() == null) {
            carouselItem.setStatus(1);
        }


        carouselItemMapper.insert(carouselItem);
        return carouselItem;
    }

    /**
     * 更新轮播图项
     */
    @Override
    public boolean updateCarouselItem(CarouselItem carouselItem) {
        if (carouselItem.getId() == null) {
            return false;
        }

        // 获取原记录，确保scene不被错误修改
        CarouselItem existItem = carouselItemMapper.selectById(carouselItem.getId());
        if (existItem == null ) {
            return false;
        }

        // 不允许修改scene
        carouselItem.setScene(existItem.getScene());

        return carouselItemMapper.updateById(carouselItem) > 0;
    }

    /**
     * 删除轮播图项
     */
    @Override
    public boolean deleteCarouselItem(Long id) {
        // 使用逻辑删除
        CarouselItem item = new CarouselItem();
        item.setId(id);
        return carouselItemMapper.updateById(item) > 0;
    }

    /**
     * 更新轮播图项排序
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCarouselItemSort(List<CarouselItem> items) {
        if (items == null || items.isEmpty()) {
            return false;
        }

        for (CarouselItem item : items) {
            if (item.getId() == null || item.getSort() == null) {
                continue;
            }

            CarouselItem updateItem = new CarouselItem();
            updateItem.setId(item.getId());
            updateItem.setSort(item.getSort());
            carouselItemMapper.updateById(updateItem);
        }

        return true;
    }

    @Override
    public CarouselImageUploadRequest uploadCarouselImage(MultipartFile file) {
        // 使用通用的图片上传服务，指定存储在carousel子目录
        UploadPictureResult uploadResult = filePictureUpload.uploadPicture(file, "carousel");

        // 转换为轮播图专用DTO
        CarouselImageUploadRequest result = new CarouselImageUploadRequest();
        result.setImageUrl(uploadResult.getUrl());
        result.setOriginalFilename(file.getOriginalFilename());
        return result;
    }
}